package com.viroyal.monitorlib;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.lztek.toolkit.Lztek;
import com.suntiago.baseui.utils.log.CrashHandler;
import com.suntiago.baseui.utils.log.Slog;
import com.viroyal.monitorlib.entity.HBbean;
import com.viroyal.monitorlib.entity.RestartRes;
import com.viroyal.monitorlib.entity.UpdateS;
import com.viroyal.monitorlib.entity.UploadRes;
import com.viroyal.monitorlib.entity.UploadTable;
import com.viroyal.monitorlib.entity.rx.RxInstall;
import com.viroyal.monitorlib.entity.rx.UpdateRes;
import com.viroyal.monitorlib.network.Api;
import com.viroyal.monitorlib.network.BaseRspObserver;
import com.viroyal.monitorlib.network.UpdateApi;
import com.viroyal.monitorlib.network.iot.IOTCallback;
import com.viroyal.monitorlib.network.iot.IOTClient;
import com.viroyal.monitorlib.network.iot.IOTClientI;
import com.viroyal.monitorlib.network.rsp.BaseResponse;
import com.viroyal.monitorlib.network.rsp.FileUploadResponse;
import com.viroyal.monitorlib.network.socket.ClientSocket;
import com.viroyal.monitorlib.network.socket.IotMessage;
import com.viroyal.monitorlib.network.upload.UploadRepository;
import com.viroyal.monitorlib.screenshot.ConstantsYJ;
import com.viroyal.monitorlib.screenshot.Shotter;
import com.viroyal.monitorlib.service.MainStartService;
import com.viroyal.monitorlib.utils.AppUtils;
import com.viroyal.monitorlib.utils.DataCleanManager;
import com.viroyal.monitorlib.utils.FileUtils;
import com.viroyal.monitorlib.utils.MyActivityManager;
import com.viroyal.monitorlib.utils.SPUtils;
import com.ys.rkapi.MyManager;

import org.kymjs.kjframe.KJDB;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.viroyal.monitorlib.network.Api.NETTY_HOST;
import static com.viroyal.monitorlib.network.Api.NETTY_HOST_PORT;
import static com.viroyal.monitorlib.service.MainStartService.MSG_TOP_PACKAGE;

/**
 * Created by zy on 2018/3/13.
 */

public class CommandControl implements UpdateSHelper.Callback, IOTCallback {
  private static final String TAG = "CommandControl";

  private UpdateSHelper mUpdateSHelper;

  private Context mContext;

  private IOTClient mIOTClient;

  private ClientSocket mClientSocket;

  private String lastpkgName = "";

  private static final boolean sUseIot = false;

  public CommandControl(Context context) {
    mContext = context;
    mUpdateSHelper = new UpdateSHelper(this, mContext);
    if (sUseIot) {
      mIOTClient = new IOTClientI(mContext);
      mIOTClient.setReceiveCallback(this);
    } else {
      mClientSocket = new ClientSocket(context.getApplicationContext());
      mClientSocket.setDevId(Api.get().getDeviceId(mContext));
      reconnect();
    }

    RxBus.get().register(this);
  }

  private void reconnect() {
    Slog.d(TAG, "reconnect:mClientSocket:NETTY_HOST:" + NETTY_HOST + " NETTY_HOST_PORT:" + NETTY_HOST_PORT);
    if (!TextUtils.isEmpty(NETTY_HOST) && NETTY_HOST_PORT != 0) {
      mClientSocket.disconnect();
      mClientSocket.connect(NETTY_HOST, NETTY_HOST_PORT);
    }
  }


  //发送消息
  public void send(String a) {
    Slog.d(TAG, "send   [a]:" + a);
    if (sUseIot) {
      mIOTClient.send(a);
    } else {
      mClientSocket.sendData(a);
    }
  }

  //发送消息
  private void sendrrpc(String a, long rrpcId) {
    Slog.d(TAG, "sendrrpc   [a]:" + a + " rrpcId:" + rrpcId + "");
    if (sUseIot) {
      mIOTClient.sendRrpc(a, rrpcId);
    } else {
      mClientSocket.sendData(a, rrpcId);
    }
  }

  //接收消息
  @Override
  public void receive(String msg) {
    //收到更新的消息
    Slog.d(TAG, "receive  [msg]:" + msg);
    try {
      mUpdateSHelper.addS(new Gson().fromJson(msg, UpdateS.class));
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  @Override
  public void receive(String msg, long messageId) {

    Slog.d(TAG, "receive  [msg, messageId]:" + msg + " messageId:" + messageId + "");
    try {
      UpdateS updateS = new Gson().fromJson(msg, UpdateS.class);
      updateS.mrrpcId = messageId;
      mUpdateSHelper.addS(updateS);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  //安装操作命令发送命令执行完成回复
  public void updateInstallDownloadRes(String pkg_name, int progress) {
    UpdateRes res = mUpdateSHelper.resByPkgName(pkg_name);
    if (res != null) {
      res.status = status_downloading;
      res.download_progress = progress;
      {
        //安装进度改为接口方式回调，不在使用socket方式回应
        //send(res.toString());
        instsallProgress(res);
      }
    } else {
      Slog.d(TAG, "updateInstallDownloadRes  [pkg_name, progress]:res == null");
    }
  }

  //安装操作命令发送命令执行完成回复
  private void updateInstallRes(String pkg_name, int status) {

    UpdateRes res = mUpdateSHelper.resByPkgName(pkg_name);
    if (res != null) {
      res.status = status;
      res.download_progress = 0;
      {
        //安装进度改为接口方式回调，不在使用socket方式回应
        if (status == status_install_receive) {
          send(res.toString());
        } else {
          instsallProgress(res);
        }
      }
    } else {
      Slog.d(TAG, "updateInstallRes  [pkg_name, status]:" + "res == null");
    }
  }

  //发送命令执行完成回复
  private void uploadResUpload(String id, String action, String file_url, String pkg_name) {
    UploadRes uploadRes = new UploadRes(mContext, id, action, file_url, pkg_name);
    UpdateS us = mUpdateSHelper.findByid(id);

    //us.mrrpcId
    //如果是截图命令，发送rrpc指令
    if (us != null && us.mrrpcId != 0) {
      sendrrpc(uploadRes.toString(), us.mrrpcId);
      Slog.d(TAG, "uploadResUpload  [id, action, file_url, pkg_name]:" + us.mrrpcId);
    } else {
      if ("log-upload".equals(action)) {
        if (file_url.equals("-1")) {
          return;
        }
        //异常log上报
        Api.get().getApi(UpdateApi.class)
            .reportCrash(Api.get().getSchoolId(), Api.get().getDeviceId(mContext), uploadRes)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseRspObserver<>(BaseResponse.class, rsp -> {
              if (rsp.error_code == 1000) {
                Slog.e(TAG, "error_code=" + rsp.error_code + "异常上报成功");
                //DataCleanManager.cleanCustomCache(CrashHandler.getInstance().getCrashLogPath());
              } else {
                Slog.e(TAG, "error_code=" + rsp.error_code + "异常上报失败");
              }
            }));
      } else {
        send(uploadRes.toString());
      }
    }
  }

  //发送命令执行完成回复
  public void updateRestart(String id, String pkg_name, int status) {
    RestartRes restartRes = new RestartRes(mContext, id, "restart", status, pkg_name);
    UpdateS us = mUpdateSHelper.findByid(id);
    sendrrpc(restartRes.toString(), us.mrrpcId);
  }

  //发送命令执行完成回复
  private void updateResTopError(String pkg_name, int count) {
    UploadRes uploadRes = new UploadRes(mContext, null, "top-error", null, pkg_name);
    uploadRes.minutes_count = count + "";
    Api.get().getApi(UpdateApi.class)
        .reportTopError(Api.get().getSchoolId(), Api.get().getDeviceId(mContext), uploadRes)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new BaseRspObserver<>(BaseResponse.class, rsp -> {
          if (rsp.error_code != 1000) {
            Slog.e(TAG, "error_code=" + rsp.error_code);
          }
        }));
  }

  //自检更新APP
  public void upLoadApp(String action, long id, int uninstall, String url, int version_code, String pkg_name, int is_coerce) {
    UpdateS updateS = new UpdateS().upLoadApp(action, id, uninstall, url, version_code, pkg_name, is_coerce);
    mUpdateSHelper.addS(updateS);
  }

  //1-安装成功 2-其他原因安装失败  3-无法自动安装需要手动介入 4-版本已存在 5-下载失败 6-卸载失败
  //0 收到安装命令

  private final static int status_install_receive = 0;
  private final static int status_install_success = 1;
  private final static int status_accessibility_off = 3;
  private final static int status_already_installed = 4;
  private final static int status_download_url_null = 5;

  //安装任务的的反馈状态
  private final static int status_is_uninstall = 11;
  private final static int status_downloading = 12;

  //top处理
  //安装的apk

  //安装操作大致状态
  //收到新消息
  @Override
  public void handleNew(UpdateS updateS) {
    Slog.d(TAG, "handleNew  [updateS]:" + updateS.toString());
    if ("install".equals(updateS.action)) {
      MainStartService.MyHandler hander = MainStartService.mMyHandler;
      hander.removeMessages(MSG_TOP_PACKAGE);
      updateInstallRes(updateS.pkg_name, status_install_receive);
      //安装的命令
      PackageInfo packageInfo = AppUtils.getPackageInfo(mContext, updateS.pkg_name);
      if (packageInfo != null && packageInfo.versionCode >= updateS.version_code) {
        Slog.d(TAG, "handleNew  [updateS]:VersionCode installed:" + packageInfo.versionCode);
        //已经安装过了
        updateInstallRes(updateS.pkg_name, status_already_installed);
      } else {
        //需要更新
        if (TextUtils.isEmpty(updateS.url)) {
          //下载地址为空
          updateInstallRes(updateS.pkg_name, status_download_url_null);
          return;
        } else {
          //需要卸载
          if (updateS.uninstall == 1 && AppUtils.isAppInstalled(mContext, updateS.pkg_name)) {
            //先执行卸载操作
            AppModel.get().uninstall(updateS.pkg_name);
            updateInstallRes(updateS.pkg_name, status_is_uninstall);
            return;
          }
        }
        //判断当前是否需要强制更新
        if (updateS.is_force_upgrade == 0) {
          showUpdateDialog(updateS);
        } else if (updateS.is_force_upgrade == 1) {
          updateInstallRes(updateS.pkg_name, status_downloading);
          AppModel.get().download(updateS.url, updateS.pkg_name);
        }
      }
    } else if ("capture".equals(updateS.action)) {
      //截图命令
      if (HBbean.build().id(updateS.id).top(mContext).mTopActivityInfoList.get(0).packageName.contains("viroyal") &&
          HBbean.build().id(updateS.id).top(mContext).mTopActivityInfoList.get(0).packageName.equals(mContext.getPackageName())) {

        if (android.os.Build.VERSION.SDK_INT >= 21) {
          //调用系统提供方法截图(Shotter)
          sendCapture(updateS);
        } else {
          //调用普通方法截图(MonitorBaseActivity)
          sendCaptureBitmap(updateS);
        }
      } else if (HBbean.build().id(updateS.id).top(mContext).mTopActivityInfoList.get(0).packageName.equals("")) {
        if (!lastpkgName.equals("")) {
          if (android.os.Build.VERSION.SDK_INT >= 21) {
            //调用系统提供方法截图(Shotter)
            sendCapture(updateS);
          } else {
            //调用普通方法截图(MonitorBaseActivity)
            sendCaptureBitmap(updateS);
          }
        }
      } else {
        Slog.d(TAG, "capture:app not at the top");
      }
    } else if ("top".equals(updateS.action)) {
      //top处理,获取设备应用的状态，栈的情况
      if (updateS.mrrpcId != 0) {
        sendrrpc(HBbean.build().id(updateS.id).top(mContext).dev(mContext).toString(), updateS.mrrpcId);
      } else {
        send(HBbean.build().id(updateS.id).top(mContext).dev(mContext).toString());
      }
    } else if ("pkg_info".equals(updateS.action)) {
      if (updateS.mrrpcId != 0) {
        sendrrpc(HBbean.build().pkgInfo().id(updateS.id).dev(mContext).toString(), updateS.mrrpcId);
      } else {
        send(HBbean.build().pkgInfo().id(updateS.id).dev(mContext).toString());
        Toast.makeText(mContext, HBbean.build().pkgInfo().id(updateS.id).dev(mContext).toString(), Toast.LENGTH_LONG).show();
      }
    } else if ("restart".equals(updateS.action)) {
      Slog.d(TAG, "HandleNew:restart");
      if (HBbean.build().id(updateS.id).top(mContext).dev(mContext).toString().contains(updateS.pkg_name)) {
        Slog.d(TAG, "HandleNew:restart App");
        PackageManager mPackageManager = mContext.getPackageManager();
        Slog.d(TAG, "HandleNew:App is not running,start App");
        updateRestart(String.valueOf(updateS.id), updateS.pkg_name, 1);
        Intent intent = mPackageManager.getLaunchIntentForPackage(updateS.pkg_name);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
      } else {
        Slog.d(TAG, "HandleNew:App not found");
        updateRestart(String.valueOf(updateS.id), updateS.pkg_name, -1);
      }
    } else if ("get-log".equals(updateS.action)) {
      Slog.d(TAG, "HandleNew:get-log");
      if (HBbean.build().id(updateS.id).top(mContext).dev(mContext).toString().contains(updateS.pkg_name)) {
//                if (updateS.pkg_name.equals(mContext.getPackageName())) {
//
//                }
        Intent getLog = new Intent("com.viroyal.permission.getlog");
        getLog.putExtra("id", updateS.id + "");
        getLog.putExtra("pkgName", updateS.pkg_name);
        mContext.sendBroadcast(getLog);
      } else {
        Slog.d(TAG, "HandleNew:App not found");
        uploadResUpload(String.valueOf(updateS.id), "get-log", "", updateS.pkg_name);
      }
    } else if ("forward".equals(updateS.action)) {
      Intent intent = new Intent("com.viroyal.permission.viroyal.receive.netty");
      intent.putExtra("content", updateS.data);
      mContext.sendBroadcast(intent);
      sendrrpc("{\"error_code\":1000}", updateS.mrrpcId);
    } else if ("clear_cache".equals(updateS.action)) {
      //清除缓存
      DataCleanManager.cleanApplicationData(mContext);
      if (updateS.mrrpcId != 0) {
        sendrrpc("{\"error_code\":1000}", updateS.mrrpcId);
      } else {
        send("{\"error_code\":1000}");
      }
      Toast.makeText(mContext, "清理缓存成功", Toast.LENGTH_SHORT).show();
    } else if ("restart_equipment".equals(updateS.action)) {
      //重启设备
      if (updateS.mrrpcId != 0) {
        sendrrpc("{\"error_code\":1000}", updateS.mrrpcId);
      } else {
        send("{\"error_code\":1000}");
      }
      switch (updateS.pkg_name) {
        case "4":
          //重启设备(大屏)
          Lztek lztek = Lztek.create(mContext);
          lztek.hardReboot();
          break;
        case "15"://考勤(双目)
          Intent intent = new Intent("com.hra.reboot");
          mContext.sendBroadcast(intent);
          break;
        case "0":
          if (android.os.Build.MODEL.equals("T2") || android.os.Build.MODEL.equals("T3") || android.os.Build.MODEL.equals("T6")) {//华瑞安班牌
            intent = new Intent("com.hra.reboot");
            mContext.sendBroadcast(intent);
          } else if (android.os.Build.MODEL.equals("rk3288")) {//星马班牌
            MyManager manager = MyManager.getInstance(mContext);
            manager.reboot();
          }
          break;
      }
    }
  }

  private void showUpdateDialog(UpdateS updateS) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivityManager.getInstance().getCurrentActivity());
    alertDialog.setTitle("升级提示");
    alertDialog.setMessage("发现新的版本,是否现在更新?");
    alertDialog.setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss());
    alertDialog.setPositiveButton("马上更新", (dialogInterface, i) -> {
      dialogInterface.dismiss();
      updateInstallRes(updateS.pkg_name, status_downloading);
      AppModel.get().download(updateS.url, updateS.pkg_name);
    });
    alertDialog.show();
  }

  private void sendCapture(UpdateS updateS) {
    Slog.d("Screenshot :", "Screenshot start :");

    if (SPUtils.getInstance(mContext).getIntent() == null) {
      RxBus.get().post(ConstantsYJ.RxTag.SCREENSHOT, "");//传递给mainActivity获取截图权限
    }
    try {
      Thread.sleep(800);
    } catch (Exception e) {
      e.printStackTrace();
    }
    Shotter shotter = new Shotter(mContext, -1, SPUtils.getInstance(mContext).getIntent());
    shotter.startScreenShot(new Shotter.OnShotListener() {
      @Override
      public void onFinish(String path) {
        Intent intent = new Intent("com.viroyal.permission.capture_complete");
        intent.putExtra("id", String.valueOf(updateS.id));
        intent.putExtra("pkgName", AppUtils.getPackageName(mContext));
        intent.putExtra("path", path);
        intent.putExtra("ret", "");
        intent.putExtra("msg", "");
        mContext.sendBroadcast(intent);

        shotter.cancelTask();
      }

      @Override
      public void onerror() {
        Slog.d("Screenshot :", "receive  [msg]:" + "截图失败");
        shotter.cancelTask();
      }
    });
  }

  public void sendCaptureBitmap(UpdateS updateS) {
    Intent capture = new Intent("com.viroyal.permission.capture");
    capture.putExtra("id", updateS.id + "");
    capture.putExtra("pkgName", updateS.pkg_name);
    mContext.sendBroadcast(capture);
  }

  public void apkInstalled(RxInstall rxInstall) {
    if (rxInstall.action.equals("install")) {
      if (rxInstall.success) {
        updateInstallRes(rxInstall.pkg_name, status_install_success);
      }
    } else if (rxInstall.action.equals("uninstall")) {
      //卸载成功，重新开始安装。
      if (rxInstall.success) {
        mUpdateSHelper.unstalled(rxInstall.pkg_name);
      }
    }
  }

  public void hostChange() {
//        Slog.d(TAG, "hostChange  []:");
//        if (mClient != null) {
//            mClient.close();
//        }
//        connect();
  }

  //文件压缩操作
  private void checkCompress(String filepath) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2;
    Bitmap bm = BitmapFactory.decodeFile(filepath, options);

    Slog.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)
        + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight());
    FileOutputStream fos;
    try {
      // 判断手机设备是否有SD卡
      boolean isHasSDCard = Environment.getExternalStorageState().equals(
          android.os.Environment.MEDIA_MOUNTED);
      if (isHasSDCard) {
        // SD卡根目录
        File sdRoot = Environment.getExternalStorageDirectory();
        File file = new File(filepath);
        fos = new FileOutputStream(file);
      } else
        throw new Exception("创建文件失败!");

      bm.compress(Bitmap.CompressFormat.JPEG, 50, fos);
      fos.flush();
      fos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  //上传
  public void upload(final String sid, String filepath, final String pkgName, final String action) {
    if (action.equals("capture")) {
      checkCompress(filepath);
    }
    UploadRepository.upload(mContext, filepath, pkgName,
        "monitor_" + action + "_" + System.currentTimeMillis() + "",
        new UploadRepository.ApiCallback() {
          @Override
          public void onResult(FileUploadResponse response) {
            Slog.d(TAG, "upload call  [response]:" + response.toString());
            if (response.error_code == 1000) {
              uploadResUpload(sid, action, response.extra, pkgName);
              //删除 记录
              KJDB.getDefaultInstance().deleteByWhere(UploadTable.class, "id_server = \"" + sid + "\"");
              deleteCache();
            } else {
              Slog.e(TAG, "call:FileUploadResponse error ");
              uploadResUpload(sid, action, response.error_code + "", pkgName);
              List<UploadTable> lu = KJDB.getDefaultInstance().findAllByWhere(UploadTable.class, "id_server = \"" + sid + "\"");
              if (lu != null && lu.size() > 0) {
                UploadTable u = lu.get(0);
                u.status = 4;
                KJDB.getDefaultInstance().update(u);
              } else {
                Slog.d(TAG, "onResult  [response]:u == null");
              }
            }
          }

          @Override
          public void onResult(String s) {
            Slog.d(TAG, "onResult  [s]:" + s);
          }
        });
  }

  private void deleteCache() {
    List<UploadTable> list = KJDB.getDefaultInstance().findAllByWhere(UploadTable.class,
        "status = 2 AND update_time < " + (System.currentTimeMillis() - 1000 * 60 * 60 * 24));
    if (list != null && list.size() > 0) {
      for (UploadTable uploadTable : list) {
        FileUtils.delFile(uploadTable.local_path);
        KJDB.getDefaultInstance().delete(uploadTable);
      }
    }
  }

  /**
   * 检查网络状态
   * <p>
   * param a
   *
   * @return
   * @throws
   */
  public void checkConnect() {
    //检查iot状态
    if (mIOTClient != null) {
      mIOTClient.checkConnect();
    }
    //检查上传的情况
    List<UploadTable> list = KJDB.getDefaultInstance().findAllByWhere(UploadTable.class, "status = 4");
    if (list != null && list.size() > 0) {
      Slog.d(TAG, "checkConnect  []:UploadTable.size()" + list.size());
      UploadTable u = list.get(0);
      u.status = 1;
      KJDB.getDefaultInstance().update(u);
      upload(u.id_server, u.local_path, u.pkg_name, u.action);
    } else {
      Slog.d(TAG, "checkConnect  []:UploadTable.size() 0");
    }
  }

  public void checkInstall() {
    //检测已装app
    HBbean pkgInfo = new HBbean();
    pkgInfo = HBbean.build().dev(mContext);
    String lastpkgInfo = "";
    if (TextUtils.isEmpty(SPUtils.getInstance(mContext).get("installed"))) {
      lastpkgInfo = "";
    } else {
      lastpkgInfo = SPUtils.getInstance(mContext).get("installed");
    }
    if (!pkgInfo.toString().equals(lastpkgInfo) || !isInstalledUpdate) {
      lastpkgInfo = pkgInfo.toString();
      Slog.d(TAG, "checkInstall [installed]:" + lastpkgInfo);
      SPUtils.getInstance(mContext).put("installed", lastpkgInfo);
      getInstalled(pkgInfo);
    } else {
      Slog.d(TAG, "checkInstall [installed]:");
    }
  }

  public void checkTop(int m) {
    //检测前台app
    HBbean appName = new HBbean();
    appName = HBbean.build().top(mContext);
    if (appName.mTopActivityInfoList.size() > 0) {
      if ((!appName.mTopActivityInfoList.get(0).appName.equals(lastpkgName) && !appName.mTopActivityInfoList.get(0).appName.equals("")) || !isTopUpdate) {
        if (m != 103) {
          Slog.d(TAG, "checkTop [top]:lastTopPkgName:" + lastpkgName);
          getTopApp(appName);
          String pkgname = SPUtils.getInstance(mContext.getApplicationContext()).get("pkg");
          Slog.d(TAG, "checkTop [top-error]:" + pkgname);
          updateResTopError(pkgname, 1);
        }
        lastpkgName = appName.mTopActivityInfoList.get(0).appName;
        if (!TextUtils.isEmpty(SPUtils.getInstance(mContext.getApplicationContext()).get("connect_status"))) {
          String status = SPUtils.getInstance(mContext.getApplicationContext()).get("connect_status");
          if (status.contains("DEV_CONNECTED")) {
          } else {
            Slog.d(TAG, "checkTop [top]: disconnected");
          }
        } else {
          Slog.d(TAG, "checkTop [top]: have not been connected");
        }
      } else {
        Slog.d(TAG, "checkTop [top]:" + lastpkgName);
      }
    } else {
      Slog.d(TAG, "checkTop [top]: null");
    }
  }

  private boolean isTopUpdate = false;

  private void getTopApp(HBbean top) {
    Api.get().getApi(UpdateApi.class)
        .getTopAppList(Api.get().getSchoolId(), Api.get().getDeviceId(mContext), Api.get().getDeviceId(mContext), top)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<BaseResponse>() {
          @Override
          public void onCompleted() {
          }

          @Override
          public void onError(Throwable e) {
            isTopUpdate = false;
            Slog.e(TAG, "getTopApp onError  [e]:" + e.getMessage());
            //如果加载失败，稍后重新加载
          }

          @Override
          public void onNext(BaseResponse appsResponse) {
            if (appsResponse.error_code == 1000) {
              isTopUpdate = true;
              Slog.e(TAG, "getTopApp onNext " +
                  appsResponse.error_code + appsResponse.error_msg);
              Slog.d(TAG, "getTopApp send:[top]" + top.toString());
            } else {
              isTopUpdate = false;
              Slog.e(TAG, "getTopApp onNext " +
                  appsResponse.error_code + appsResponse.error_msg);
            }
          }
        });
  }

  private boolean isInstalledUpdate = false;

  private void getInstalled(HBbean ins) {
    Api.get().getApi(UpdateApi.class)
        .getInstalled(Api.get().getSchoolId(), Api.get().getDeviceId(mContext), ins.dev_sn, ins)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<BaseResponse>() {
          @Override
          public void onCompleted() {
          }

          @Override
          public void onError(Throwable e) {
            isInstalledUpdate = false;
            Slog.e(TAG, "getInstalled onError  [e]:" + e.getMessage());
            //如果加载失败，稍后重新加载
          }

          @Override
          public void onNext(BaseResponse appsResponse) {
            if (appsResponse.error_code == 1000) {
              isInstalledUpdate = true;
              Slog.e(TAG, "getInstalled onNext " +
                  appsResponse.error_code + appsResponse.error_msg);
              Slog.d(TAG, "getInstalled send:[installed]" + ins.toString());
            } else {
              isInstalledUpdate = false;
              Slog.e(TAG, "getInstalled onNext " +
                  appsResponse.error_code + appsResponse.error_msg);
            }
          }
        });
  }


  private void instsallProgress(UpdateRes ins) {
    Slog.d(TAG, "instsallProgress  [ins]:");
    Api.get().getApi(UpdateApi.class)
        .installProgress(Api.get().getSchoolId(), Api.get().getDeviceId(mContext), ins.dev_sn, ins)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<BaseResponse>() {
          @Override
          public void onCompleted() {
          }

          @Override
          public void onError(Throwable e) {
            Slog.e(TAG, "instsallProgress onError  [e]:" + e.getMessage());
            //如果加载失败，稍后重新加载
          }

          @Override
          public void onNext(BaseResponse appsResponse) {
            if (appsResponse.error_code == 1000) {
              Slog.e(TAG, "instsallProgress onNext " +
                  appsResponse.error_code + appsResponse.error_msg);
              Slog.d(TAG, "instsallProgress send:[installed]" + ins.toString());
            } else {
              Slog.e(TAG, "instsallProgress onNext " +
                  appsResponse.error_code + appsResponse.error_msg);
            }
          }
        });
  }

  @Subscribe(
      thread = EventThread.MAIN_THREAD
  )
  public void onRecvSocketIotMessage(IotMessage iotMessage) {
    try {
      if (iotMessage.topic != null && iotMessage.topic.startsWith("/rrpc")) {
        int index = iotMessage.topic.lastIndexOf("/");
        long messageId = Long.parseLong(iotMessage.topic.substring(index + 1));

        UpdateS updateS = new Gson().fromJson(iotMessage.payload, UpdateS.class);
        updateS.mrrpcId = messageId;
        mUpdateSHelper.addS(updateS);
      } else {
        mUpdateSHelper.addS(new Gson().fromJson(iotMessage.payload, UpdateS.class));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void checkTopPackage() {
//        if (!SPUtils.getInstance(mContext).get("pkg").equals(AppUtils.getPackageName(mContext))){
    //如果APP进程存在且APP不在前台,将应用调用至前台
    ActivityManager activtyManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfos = activtyManager.getRunningTasks(100);
    for (ActivityManager.RunningTaskInfo runningTaskInfo : runningTaskInfos) {
      if (mContext.getPackageName().equals(runningTaskInfo.topActivity.getPackageName())) {
        Slog.d(TAG, "runningTaskInfo.topActivity :" + runningTaskInfo.topActivity.getPackageName());
        SPUtils.getInstance(mContext.getApplicationContext()).put("pkg", runningTaskInfo.topActivity.getPackageName());
        SPUtils.getInstance(mContext.getApplicationContext()).put("class", runningTaskInfo.topActivity.getClassName());
        activtyManager.moveTaskToFront(runningTaskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
        return;
      }
    }
    Slog.d(TAG, "checkTopPackage :" + runningTaskInfos.toString());
    //如果APP进程不存在,重启APP
    PackageManager mPackageManager = mContext.getPackageManager();
    Intent intent = mPackageManager.getLaunchIntentForPackage(AppUtils.getPackageName(mContext));
    mContext.startActivity(intent);
//        }
  }
}